import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;
// 回显服务器
public class UdpEchoServer {
    //先创建一个DatagramSocket对象，后续操作网卡的基础
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException {
        //服务器需要手动设置端口号
        socket = new DatagramSocket(port);
        //如果为空则为系统自动分配端口号
//        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //1.接收请求数据并解析
                //创建一个数据报以接收客户端发来的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
                //当前数据报为二进制文件所以需要进行解析为字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.对数据进行计算并返回结果
            String responce = process(request);
            //3.打包数据并返回给客户端
                //将计算后的结果打包为数据报
            DatagramPacket responcePacket = new DatagramPacket(responce.getBytes(),responce.getBytes().length,requestPacket.getSocketAddress());


                //把结果发回给客户端（响应）
            socket.send(responcePacket);
            //4.打印日志
            System.out.printf("[%s:%d] req=%s, res=%s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,responce);
        }
    }
    //对请求进行处理
    private String process(String request) {
        System.out.println(request);
        Scanner scanner = new Scanner(System.in);
        String responce = scanner.next();
        return responce;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        //启动服务器
        server.start();
    }
}
